<template>
    <div class="flex justify-center items-center h-screen w-screen">
        <div class="w-[75%] h-[75%] grid grid-cols-5 gap-4">
            <ElCard class="flex flex-col min-h-0 col-span-3" body-class="h-full min-h-0">
                <div class="h-full flex flex-col justify-center items-center overflow-hidden">
                    <img class="min-h-0 h-auto w-full rounded" src="/image/login.png"></img>
                    <p class="text-2xl font-bold">商银通智能平台</p>
                    <p class="text-xl">帮你领悟更多知识</p>
                </div>
            </ElCard>
            <ElCard class="col-span-2 h-full  min-h-0" body-class="h-full min-h-0">
                <div class="h-full min-h-0 flex-1 flex flex-col justify-center  gap-4">
                    <p class="text-center text-2xl font-bold">{{ (isLogin ? '登录' : '注册') + '账号' }}</p>
                    <div class="min-h-0 overflow-x-hidden">
                        <ElScrollbar noresize class="px-10 overflow-x-hidden">
                            <div class="w-full flex flex-col justify-center gap-4 overflow-x-hidden">
                                <ElForm ref="formRef" label-width="auto" label-position="right" :model="form" hide-required-asterisk
                                    :rules="rules">
                                    <ElFormItem prop="username" label="用户名" v-if="!isLogin">
                                        <ElInput v-model="form.username" placeholder="请输入用户名"></ElInput>
                                    </ElFormItem>
                                    <ElFormItem prop="account" label="账号">
                                        <ElInput v-model="form.account" placeholder="请输入账号"></ElInput>
                                    </ElFormItem>
                                    <ElFormItem prop="password" label="密码">
                                        <ElInput show-password v-model="form.password" placeholder="请输入密码"></ElInput>
                                    </ElFormItem>
                                    <ElFormItem prop="repassword" label="密码" v-if="!isLogin">
                                        <ElInput show-password v-model="form.repassword" placeholder="请再次输入密码">
                                        </ElInput>
                                    </ElFormItem>
                                    <ElFormItem prop="class" label="公司">
                                        <ElSelect v-model="form.class" :options="classList"
                                            :props="{ label: 'name', value: 'id' }" @change="getCourseAPI"
                                            placeholder="请选择公司">
                                        </ElSelect>
                                    </ElFormItem>
                                    <ElFormItem prop="course" label="部门">
                                        <ElSelect v-model="form.course" :options="courseList"
                                            :props="{ label: 'name', value: 'id' }" placeholder="请选择部门"></ElSelect>
                                    </ElFormItem>
                                    <ElFormItem prop="code" label="验证码" v-if="isLogin">
                                        <div class="flex gap-2">
                                            <ElInput size="default" v-model="form.code" placeholder="请输入验证码"></ElInput>
                                            <img class="w-auto h-8" @click="getCaptchaAPI" :src="captcha" alt="">
                                        </div>
                                    </ElFormItem>
                                    <ElFormItem prop="avatar" label="头像" v-if="!isLogin">
                                        <p class="w-full whitespace-normal break-words">{{ form.avatar }}</p>
                                        <UploadImg ref="uploadImg" v-model="form.avatar"></UploadImg>
                                    </ElFormItem>
                                </ElForm>
                                <ElButton @click="submit" type="primary" class="w-full">{{ (isLogin ? '登录' : '注册') +
                                    '账号' }}
                                </ElButton>
                                <div class="w-full flex justify-end">
                                    <ElButton type="primary" link
                                        @click="() => { isLogin = !isLogin; formRef.resetFields() }">
                                        {{ isLogin
                                            ? '注册账号>' : '登录账号>' }}
                                    </ElButton>
                                </div>
                            </div>
                        </ElScrollbar>
                    </div>
                </div>
            </ElCard>
        </div>
    </div>
    <ElButton link type="primary" size="large" class="!m-0 absolute bottom-5 right-5" @click="toggleDark()">
        <ElIcon :size="20" v-if="!isDark">
            <Moon />
        </ElIcon>
        <ElIcon :size="20" v-else>
            <Sunny />
        </ElIcon>
    </ElButton>
</template>

<script setup lang='ts' name=''>
import UploadImg from '@/components/UploadImg.vue'
import { Moon, Sunny } from '@element-plus/icons-vue';
import { getClass, getCourse, getCaptcha, getCaptchaID, login, register } from '@/api/login';
import router from '@/router';
import { ElIcon, ElCard, ElForm, ElFormItem, ElButton, ElInput, ElSelect, ElMessage, ElScrollbar } from 'element-plus';
import { ref } from 'vue';
import { useDark, useToggle } from '@vueuse/core'
const isDark = useDark()
const toggleDark = useToggle(isDark)
/** 表单实例 */
const formRef = ref()
/** 上传图片实例 */
const uploadImg = ref()
/** 登录注册flag */
const isLogin = ref(true);
/** 表单数据 */
const form = ref({
    username: '',
    account: '',
    password: '',
    repassword: '',
    class: '',
    course: '',
    code: '',
    codeId: '',
    avatar: '',
    avatarUrl: ''
});
/** 验证码 */
const captcha = ref()
/** 表单验证规则 */
const rules = ref({
    username: [
        { required: true, message: '请输入用户名', trigger: 'blur' },
        { min: 1, max: 18, message: '用户名长度应在1-18位之间', trigger: 'blur' },
    ],
    account: [
        { required: true, message: '请输入账号', trigger: 'blur' },
        { min: 6, max: 18, message: '账号长度应在6-18位之间', trigger: 'blur' },
    ],
    password: [
        { required: true, message: '请输入密码', trigger: 'blur' },
        { min: 6, max: 18, message: '密码长度应在6-18位之间', trigger: 'blur' },
    ],
    repassword: [
        { required: true, message: '请再次输入密码', trigger: 'blur' },
        { min: 6, max: 18, message: '密码长度应在6-18位之间', trigger: 'blur' },
    ],
    class: [
        { required: true, message: '请选择公司', trigger: 'change' },
    ],
    course: [
        { required: true, message: '请选择部门', trigger: 'change' },
    ],
    code: [
        { required: true, message: '请输入验证码', trigger: 'blur' },
    ],
    avatar: [
        { required: true, message: '请上传头像', trigger: 'change' },
    ]
})
/** 班级列表 */
const classList = ref([])
/** 课程列表 */
const courseList = ref([])

/** 获取班级列表 */
getClass().then(res => {
    classList.value = res.data
    form.value.class = res.data[0].id
    getCourseAPI(res.data[0].id)
})
/** 获取课程列表 */
async function getCourseAPI(classroomId: any) {
    await getCourse(classroomId).then(res => {
        courseList.value = res.data
        form.value.course = res.data[0].id
    })
}
/** 获取验证码 */
async function getCaptchaAPI() {
    const res = await getCaptcha()
    const blob = new Blob([res as unknown as BlobPart], { type: 'image/jpeg' });
    const imageUrl = URL.createObjectURL(blob);
    captcha.value = imageUrl;
    getCaptchaIDAPI()
}
/** 获取验证码ID */
async function getCaptchaIDAPI() {
    const res = await getCaptchaID()
    form.value.codeId = res as unknown as string
}
getCaptchaAPI()

/** 提交表单 */
async function submit() {

    /** 登录 */
    if (isLogin.value) {
        formRef.value.validate().then(async () => {
            const res = await login(form.value.account, form.value.password, form.value.class, form.value.course, form.value.code, form.value.codeId)
            if (Object.keys(res).length != 0) {
                localStorage.setItem('token', res.data.toKen)
                localStorage.setItem('username', res.data.name)
                localStorage.setItem('avatar', res.data.avatar)
                ElMessage.success('登录成功')
                router.push('/').then(() => {
                    router.go(0)
                })
            }
            /** 登录失败 重新获取验证码 */
            else {
                getCaptchaAPI()
            }
        })
    }
    /** 注册 */
    else {
        formRef.value.validate().then(async () => {
            if (form.value.password != form.value.repassword) {
                ElMessage.error('两次密码不一致')
                return
            }
            form.value.avatarUrl = await uploadImg.value.uploadImg()
            const res: any = await register(
                form.value.account,
                form.value.password,
                form.value.username,
                form.value.avatarUrl,
                form.value.class,
                form.value.course,
            )
            if (res.code == 200) {
                ElMessage.success("注册成功,请登录")
                isLogin.value = !isLogin.value
                formRef.value.resetFields()
            }
        })
    }
}
</script>

<style scoped lang="scss"></style>